import React, { useState, useEffect, useRef } from 'react';
import { Upload, Button, message, Space, Row, Col, Select, Input, Form } from 'antd';
import { UploadOutlined, PictureOutlined } from '@ant-design/icons';
import { uploadPlanetImage, setPlanetUploadType, getPlanetInfo } from '../../api/gis';
import request from '../../utils/request';

interface PlanetImageUploadProps {
  planetId: number;
}

const PlanetImageUpload: React.FC<PlanetImageUploadProps> = ({ planetId }) => {
  const [fileList, setFileList] = useState<any[]>([]);
  // const [uploading, setUploading] = useState(false);
  const [contentHeight, setContentHeight] = useState(0);
  const [imageKey, setImageKey] = useState(0); // 用于强制刷新底图
  const [hasTileData, setHasTileData] = useState(false); // 是否有瓦片数据
  const [checkingTile, setCheckingTile] = useState(true); // 是否正在检查瓦片数据
  const [planetImgType, setPlanetImgType] = useState<number>(1); // 1: JPG, 2: TIF
  const [tifOutputImg, setTifOutputImg] = useState<string>('');
  const [savingType, setSavingType] = useState<boolean>(false);
  const [form] = Form.useForm();
  const containerRef = useRef<HTMLDivElement>(null);

  // 检查瓦片数据是否存在
  const checkTileData = async (planetId: number, level: number = 1, row: number = 1, col: number = 1) => {
    try {
      setCheckingTile(true);
      const response = await request.get('/GIS/GISPlanetGetTile', {
        params: {
          planet_id: planetId,
          level: level,
          row: row,
          col: col
        }
      });

      // 如果请求成功且返回了数据，说明瓦片存在
      if (response.data && response.data.code === 200) {
        setHasTileData(true);
      } else {
        setHasTileData(false);
      }
    } catch (error: any) {
      if (error?.message === 'tile 暂未处理成功!') {
        console.error('检查瓦片数据失败:', error);
        setHasTileData(false);
      } else {
        setHasTileData(true);
      }
    } finally {
      setCheckingTile(false);
    }
  };

  // 获取星球瓦片底图URL
  const getPlanetTileUrl = (planetId: number, level: number = 1, row: number = 1, col: number = 1) => {
    return (request as any).getUrl(`/GIS/GISPlanetGetTile?planet_id=${planetId}&level=${level}&row=${row}&col=${col}`);
  };

  // 计算内容区高度
  const calculateContentHeight = () => {
    if (containerRef.current) {
      // 获取整个页面的可用高度
      const pageHeight = window.innerHeight;
      // 减去面包屑、tabs头部等的高度
      const breadcrumbHeight = 48; // 面包屑高度
      const tabsHeaderHeight = 46; // tabs头部高度
      const padding = 183; // 各种padding和margin

      const availableHeight = pageHeight - breadcrumbHeight - tabsHeaderHeight - padding;
      const minHeight = 100; // 最小高度
      const maxHeight = 700; // 最大高度

      const calculatedHeight = Math.max(Math.min(availableHeight, maxHeight), minHeight);
      setContentHeight(calculatedHeight);
    }
  };

  useEffect(() => {
    // 延迟计算，确保DOM完全渲染
    const timer = setTimeout(() => {
      calculateContentHeight();
    }, 100);

    window.addEventListener('resize', calculateContentHeight);
    return () => {
      clearTimeout(timer);
      window.removeEventListener('resize', calculateContentHeight);
    };
  }, []);

  // 获取星球详情并设置到表单
  const fetchPlanetInfo = async (planetId: number) => {
    try {
      const response = await getPlanetInfo({ id: planetId });
      if (response.code === 200 && response.data) {
        const planetData = response.data;
        // 设置表单初始值
        form.setFieldsValue({
          planet_img_type: planetData.planet_img_type || 1,
          output_img: planetData.output_img || ''
        });
        // 更新状态
        setPlanetImgType(planetData.planet_img_type || 1);
        setTifOutputImg(planetData.output_img || '');
      }
    } catch (error) {
      console.error('获取星球详情失败:', error);
      message.error('获取星球详情失败');
    }
  };

  // 当planetId变化时，检查瓦片数据和获取星球详情
  useEffect(() => {
    if (planetId) {
      checkTileData(planetId, 1, 1, 1);
      fetchPlanetInfo(planetId);
    }
  }, [planetId]);

  const customRequest = async (options: any) => {
    const { file, onSuccess: uploadOnSuccess, onError } = options;

    try {
      // setUploading(true);

      const response = await uploadPlanetImage({
        file,
        planet_id: planetId
      });

      if (response.code === 200) {
        uploadOnSuccess(response.data, file);
        message.success('底图上传成功');
        setFileList([]);
        // 强制刷新底图
        setImageKey((prev) => prev + 1);
        // 重新检查瓦片数据
        checkTileData(planetId, 1, 1, 1);
      } else {
        message.error(response.msg || '上传失败');
        onError({ msg: response.msg || '上传失败', response: response });
      }
    } catch (err: any) {
      message.error(err?.message || '网络错误');
      onError({ msg: '网络错误', response: err });
    } finally {
      // setUploading(false);
    }
  };

  // 保存底图类型配置（JPG/TIF）
  const handleSaveUploadType = async () => {
    const values = form.getFieldsValue();
    const currentType = values.planet_img_type;
    const currentOutput = values.output_img;
    if (!planetId) {
      message.error('缺少星球ID');
      return;
    }
    try {
      setSavingType(true);
      const payload: any = {
        id: planetId,
        planet_img_type: currentType
      };
      if (currentType === 2) {
        payload.output_img = currentOutput;
      }
      const res = await setPlanetUploadType(payload);
      if (res.code === 200) {
        message.success('底图类型配置已保存');
      } else {
        message.error(res.msg || '保存失败');
      }
    } catch (e: any) {
      message.error(e?.message || '网络错误');
    } finally {
      setSavingType(false);
    }
  };

  const handleFileChange = (info: any) => {
    let files = [...info.fileList];
    files = files.slice(-1); // 只允许上传一个文件
    setFileList(files);
  };

  const handleFileRemove = (file: any) => {
    setFileList((prev) => prev.filter((item) => item.uid !== file.uid));
  };

  const tileUrl = getPlanetTileUrl(planetId, 1, 1, 1);

  return (
    <div 
      ref={containerRef} 
      style={{
        height: contentHeight,
        display: 'flex',
        flexDirection: 'column',
        overflow: 'hidden',
        padding: '16px'
      }}>
      {/* 底图类型配置（JPG/TIF） */}
      <Form
        form={form}
        layout="vertical"
        onValuesChange={(changed) => {
          if (Object.prototype.hasOwnProperty.call(changed, 'planet_img_type')) {
            setPlanetImgType(changed.planet_img_type);
          }
          if (Object.prototype.hasOwnProperty.call(changed, 'output_img')) {
            setTifOutputImg(changed.output_img);
          }
        }}
        onFinish={handleSaveUploadType}
        style={{ width: '400px', marginBottom: 12 }}>
          <Form.Item name="planet_img_type" label="底图类型" rules={[{ required: true, message: '请选择底图类型' }]}>
            <Select
              options={[
                { label: 'JPG', value: 1 },
                { label: 'TIF', value: 2 }
              ]}
            />
          </Form.Item>
          <Form.Item shouldUpdate noStyle>
            {({ getFieldValue }) =>
              getFieldValue('planet_img_type') === 2 ? (
                <Form.Item name="output_img" label="TIF文件路径" rules={[{ required: true, message: '请输入TIF文件路径' }]}>
                  <Input placeholder="请输入TIF文件路径" />
                </Form.Item>
              ) : null
            }
          </Form.Item>
          <Form.Item shouldUpdate noStyle>
            {({ getFieldValue }) =>
              getFieldValue('planet_img_type') === 1 ? (
                <Form.Item required label="上传底图">
                  <div style={{ display: 'flex', alignItems: 'flex-start', gap: '16px' }}>
                    <Upload
                      listType="picture-card"
                      fileList={fileList}
                      onChange={handleFileChange}
                      onRemove={handleFileRemove}
                      customRequest={customRequest}
                      accept="image/*"
                      beforeUpload={(file) => {
                        const isImage = file.type.startsWith('image/');
                        if (!isImage) {
                          message.error('只能上传底图文件！');
                          return false;
                        }
                        return true;
                      }}>
                      {fileList.length < 1 && (
                        <div>
                          <UploadOutlined />
                          <div style={{ marginTop: 8 }}>上传底图</div>
                        </div>
                      )}
                    </Upload>

                    {/* 星球瓦片图展示 - 移动到上传按钮右侧 */}
                    <div
                      style={{
                        width: '208px', // 与上传按钮宽度一致
                        height: '104px', // 与上传按钮高度一致
                        border: '1px solid #d9d9d9',
                        borderRadius: '6px',
                        display: 'flex',
                        flexDirection: 'column',
                        justifyContent: 'center',
                        alignItems: 'center',
                        overflow: 'hidden',
                        backgroundColor: '#fafafa'
                      }}>
                      {checkingTile ? (
                        <div
                          style={{
                            display: 'flex',
                            flexDirection: 'column',
                            alignItems: 'center',
                            color: '#666',
                            fontSize: '12px'
                          }}>
                          <div>加载中</div>
                        </div>
                      ) : hasTileData ? (
                        <img
                          key={imageKey}
                          src={`${tileUrl}&t=${Date.now()}`}
                          alt={`缩略图`}
                          style={{
                            width: '100%',
                            height: '100%',
                            objectFit: 'cover',
                            borderRadius: '6px'
                          }}
                          onError={(e) => {
                            console.error('底图加载失败:', e);
                            setHasTileData(false);
                          }}
                        />
                      ) : (
                        <div
                          style={{
                            display: 'flex',
                            flexDirection: 'column',
                            alignItems: 'center',
                            color: '#999',
                            fontSize: '12px',
                            textAlign: 'center',
                            padding: '8px'
                          }}>
                          <PictureOutlined style={{ fontSize: '24px', marginBottom: '8px' }} />
                          <div>暂无底图</div>
                        </div>
                      )}
                    </div>
                  </div>
                  <div style={{ marginTop: 16 }}>
                    <Space direction="vertical" style={{ width: '100%' }}>
                      <div style={{ fontSize: '14px', color: '#666' }}>
                        <PictureOutlined style={{ marginRight: 8 }} />
                        支持格式：JPG、PNG底图格式；
                      </div>
                    </Space>
                  </div>
                </Form.Item>
              ) : null
            }
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" loading={savingType}>
              保存
            </Button>
          </Form.Item>
        </Form>
    </div>
  );
};

export default PlanetImageUpload;
